package com.wsfPro.repositoryImpl.base;

import com.wsfPro.entities.base.BaseCodeEntity;
import com.wsfPro.repository.base.BaseCodeRepository;
import com.wsfPro.util.EntityUtil;
import com.wsfPro.util.StringUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

public abstract class BaseCodeRepositoryImpl<X extends BaseCodeEntity>
    extends BaseDateRepositoryImpl<X> implements BaseCodeRepository<X> {

  @Override
  public boolean isExistCode(String code, String id) {
    try {
      String sql =
          "select count(1) from "
              + EntityUtil.getSqlTableName(getClazz())
              + " u where u.code =:code ";
      if (StringUtils.isNotBlank(id)) {
        sql += "and u.id <>:id ";
      }
      Query nativeCountQuery = entityManager.createNativeQuery(sql);
      nativeCountQuery.setParameter("code", code);
      if (id != null) {
        nativeCountQuery.setParameter("id", id);
      }
      List totalList = nativeCountQuery.getResultList();
      BigInteger total = (BigInteger) totalList.get(0);
      if (total.compareTo(BigInteger.ZERO) > 0) {
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      entityManager.close();
    }
    return false;
  }
}
